#!/usr/bin/env bash
# Used as a proxy for calling Fork.RI.exe from WSL with the path to `git-rebase-todo`
# converted to a windows path.
# Expects the environment variable FORK_RI_EXE_PATH to contain the path to Fork.RI.exe.

UNAME="$(uname -a)"
# 'uname -a' returns:
# WSL1: Linux PCNAME 4.4.0-17134-Microsoft #706-Microsoft Mon Apr 01 18:13:00 PST 2019 x86_64 x86_64 x86_64 GNU/Linux
# WSL2: Linux DESKTOP-4P30KCU 4.19.104-microsoft-standard #1 SMP Wed Feb 19 06:37:35 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
# MINGW64: MINGW64_NT-10.0 PCNAME 2.11.2(0.329/5/3) 2018-11-26 09:22 x86_64 Msys
# MINGW32: MINGW32_NT-10.0 PCNAME 2.11.2(0.329/5/3) 2018-11-26 09:22 x86_64 Msys
# MSYS: MSYS_NT-10.0 PCNAME 2.11.2(0.329/5/3) 2018-11-26 09:22 x86_64 Msys

if [[ $UNAME == *icrosoft* ]]; then
    # in a wsl shell
    WSL_BUILD=$(cmd.exe /c "systeminfo" | grep -E -i "build [0-9]+" | sed -E 's/^.*build ([0-9]+).*$/\1/I')
    if [ -z "$WSL_BUILD" ]; then
        WSL_BUILD=0
    fi

    if [ $WSL_BUILD -ge 17046 ] || [ -n "$WSL_INTEROP" ]; then
        # WSLPATH is available since WSL build 17046

        # Make sure that FORK_RI_EXE_PATH does not contain any badly escaped spaces.
        # It can happen when using Windows' short paths inside Fork's custom git instance path
        # Example: Fork is configured with "C:\Users\SURNAM~1\wslgit\bin\git.exe" instead of "C:\Users\Surname Lastname\wslgit\bin\git.exe"
        # which may be a valid use case as is does not support spaces in paths.
        # FORK_RI_EXE_PATH would contain "/mnt/c/Users/Surname/ Lastname/wslgit/bin/Fork.RI.exe" before the following sed call
        FORK_RI_EXE_PATH="$(sed 's/\/ / /g' <<< "$FORK_RI_EXE_PATH")"

        # Make sure that Fork.RI.exe is executable.
        chmod +x "$FORK_RI_EXE_PATH"

        # Call Fork.RI.exe with the path to the REBASE-TODO converted to a windows path.
        ARGS=$(wslpath -w "$@")
        "$FORK_RI_EXE_PATH" "$ARGS"
        exit $?
    else
        # ! No WSLPATH available.
        exit 1
    fi
else
    # unknown shell
    exit 1
fi
